<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Address;
use App\Models\Shop\Customer;

class AddressController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->json(Address::all_addresses());
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $customer_id = auth('api')->user()->id;

        $pca = explode(" ", $request->pca);

        Address::create([
            'customer_id' => $customer_id,
            'name' => $request->name,
            'province' => $pca[0],
            'city' => $pca[1],
            'area' => $pca[2],
            'tel' => $request->tel,
            'detail' => $request->detail,
        ]);
    }

    /***
     * 编辑地址
     * @param $id
     */
    public function edit($id)
    {
        $address = Address::find($id);
        return response()->json(compact('address'));
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $customer_id = auth('api')->user()->id;

        $pca = explode(" ", $request->pca);

        Address::where('id', $id)->update([
            'customer_id' => $customer_id,
            'name' => $request->name,
            'province' => $pca[0],
            'city' => $pca[1],
            'area' => $pca[2],
            'tel' => $request->tel,
            'detail' => $request->detail,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Address::destroy($id);
        return response()->json(Address::all_addresses());

    }

    /***
     * 设置默认地址
     * @param Request $request
     */
    public function default_address(Request $request)
    {
        $customer_id = auth('api')->user()->id;
        Customer::where('id', $customer_id)->update(['address_id' => $request->address_id]);
    }
}
